import akshare as ak
import pandas as pd

# 获取当日个股资金流向数据
def get_daily_fund_flow():
    try:
        # 获取当日资金流向数据
        fund_flow_df = ak.stock_individual_fund_flow_rank(indicator="今日")
        return fund_flow_df
    except Exception as e:
        print(f"获取资金流向数据失败: {e}")
        return None

# 保存数据到 Excel 文件
def save_to_excel(data, file_path):
    if data is None:
        print("数据为空，无法保存到 Excel")
        return
    try:
        # 保存到 Excel 文件
        data.to_excel(file_path, index=False, engine="openpyxl")
        print(f"数据已成功保存到 {file_path}")
    except Exception as e:
        print(f"保存数据到 Excel 失败: {e}")

# 简单分析
def analyze_fund_flow(data):
    if data is None:
        print("数据为空，无法进行分析")
        return

    # 数据清洗：将非数值数据转换为 NaN
    data_cleaned = data.copy()
    data_cleaned["今日主力净流入-净额"] = pd.to_numeric(data_cleaned["今日主力净流入-净额"], errors="coerce")
    data_cleaned["今日超大单净流入-净额"] = pd.to_numeric(data_cleaned["今日超大单净流入-净额"], errors="coerce")
    data_cleaned["今日大单净流入-净额"] = pd.to_numeric(data_cleaned["今日大单净流入-净额"], errors="coerce")

    # 按主力资金流入排序（流入最多的前10只股票）
    top_inflow = data_cleaned.sort_values(by="今日主力净流入-净额", ascending=False).head(10)
    print("主力资金流入最多的前10只股票：")
    print(top_inflow[["代码", "名称", "今日主力净流入-净额"]])

    # 按主力资金流出排序（流出最多的前10只股票）
    top_outflow = data_cleaned.sort_values(by="今日主力净流入-净额", ascending=True).head(10)
    print("主力资金流出最多的前10只股票：")
    print(top_outflow[["代码", "名称", "今日主力净流入-净额"]])

    return top_inflow, top_outflow

# 主函数
if __name__ == "__main__":
    # 获取当日资金流向数据
    daily_fund_flow = get_daily_fund_flow()

    if daily_fund_flow is not None:
        # 保存原始数据到 Excel 文件
        file_path = r"C:\Users\Administrator\Desktop\量化研究\python\get_daily_fund_flow\daily_fund_flow.xlsx"  # 修改为你的文件路径
        save_to_excel(daily_fund_flow, file_path)

        # 进行简单分析
        top_inflow, top_outflow = analyze_fund_flow(daily_fund_flow)

        if top_inflow is not None and top_outflow is not None:
            # 保存分析结果到 Excel 文件
            with pd.ExcelWriter(r"C:\Users\Administrator\Desktop\量化研究\python\get_daily_fund_flow\analysis_results.xlsx", engine="openpyxl") as writer:
                top_inflow.to_excel(writer, sheet_name="主力资金流入最多的前10只股票", index=False)
                top_outflow.to_excel(writer, sheet_name="主力资金流出最多的前10只股票", index=False)
            print("分析结果已成功保存到 C:\\Users\\Administrator\\Desktop\\量化研究\\python\\get_daily_fund_flow\\analysis_results.xlsx")